package com.tfjybj.itoo.teach.provider.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dmsdbj.itoo.tool.business.ItooResult;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.teach.entity.BuildingEntity;
import com.tfjybj.itoo.teach.entity.RoomEntity;
import com.tfjybj.itoo.teach.entity.ValueEntity;
import com.tfjybj.itoo.teach.model.BuildingModel;
import com.tfjybj.itoo.teach.model.FooGroupTreeModel;
import com.tfjybj.itoo.teach.provider.service.BuildingService;
import com.tfjybj.itoo.teach.provider.service.RoomService;
import com.tfjybj.itoo.teach.provider.service.ValueService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Random;

@Slf4j
/**
 * BuildingController
 * building表
 *
 * @author 段恩刚
 * @version 2.0.0
 * @since 2.0.0 2018-11-08 19:34:10
 */
@Api(tags = {"building表接口"})
@RequestMapping(value = "/building")
@RestController
public class BuildingController {

    @Resource
    private BuildingService buildingService;

    @Resource
    private RoomService roomService;

    @Resource
    private ValueService valueService;

    private String typeRoom="2";
    private String typeBuilding="1";
    private String typeBuildingType="0";

    //region 模板生成：基本增删改

    /**
     * 添加
     *
     * @param model BuildingModel
     * @return 添加的结果
     * @author 段恩刚
     * @since 2.0.0 2018-11-08 19:34:10
     */
    @ApiOperation(value = "添加")
    @PostMapping(value = {"/create"})
    public ItooResult create(@RequestBody BuildingModel model) {
        //判断建筑的名称和Code是否为空，为空的标准是 str==null 或 str.length()==0
        if (StringUtils.isEmpty(model.getName())){
            return ItooResult.build(ItooResult.FAIL, "name为空");
        }
		if (StringUtils.isEmpty(model.getCode())){
            return ItooResult.build(ItooResult.FAIL, "code为空");
        }

         // 判断添加的建筑Code和建筑名称是否重复
        String isBulidingExist=buildingService.findIdIsExist(model.getCode(),model.getName());
		if(!StringUtils.isEmpty(isBulidingExist)){
		    return ItooResult.build(ItooResult.FAIL,"添加失败，建筑名称或者Code重复！");
        }else {
            BuildingEntity buildingEntity = new BuildingEntity();
            BeanUtils.copyProperties(model, buildingEntity);
            buildingService.save(buildingEntity);
            return ItooResult.build(ItooResult.SUCCESS, "添加成功");
        }
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @return ItooResult 是否删除成功          
     * @author 段恩刚
     * @since 2.0.0 2018-11-08 19:34:10
     */
    @ApiOperation(value = "根据id删除（单个）")
    @DeleteMapping(value = {"/delete/{id}"})
    public ItooResult delete(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
        buildingService.removeById(id);
        return ItooResult.build(ItooResult.SUCCESS, "删除成功");
    }

    /**
     * 批量删除
     *
     * @param ids ids
     * @return ItooResult 批量删除是否成功结果
     * @author 段恩刚
     * @since 2.0.0 2018-11-08 19:34:10
     */
    @ApiOperation(value = "根据id批量删除")
    @DeleteMapping(value = {"/deleteByIds"})
    @ApiImplicitParam(name = "ids", value = "ids", dataType = "List<String>", required = true)
    public ItooResult deleteByIds(@RequestBody List<String> ids) {
        buildingService.removeByIds(ids);
        return ItooResult.build(ItooResult.SUCCESS, "批量删除成功");
    }

    /**
     * 编辑修改
     *
     * @param model BuildingModel
     * @return 修改后的结果
     * @author 段恩刚
     * @since 2.0.0 2018-11-08 19:34:10
     */
    @ApiOperation(value = "根据id修改building")
    @PutMapping(value = {"/modify"})
    public ItooResult modify(@RequestBody BuildingModel model) {
		if (StringUtils.isEmpty(model.getName())){
            return ItooResult.build(ItooResult.FAIL, "name为空");
        }
		if (StringUtils.isEmpty(model.getCode())){
            return ItooResult.build(ItooResult.FAIL, "code为空");
        }
            BuildingEntity buildingEntity = new BuildingEntity();
            BeanUtils.copyProperties(model, buildingEntity);
            buildingService.updateById(buildingEntity);
            return ItooResult.build(ItooResult.SUCCESS, "修改成功");
    }

    /**
     *  随机生成建筑或房间代码
     * @return 生成后的代码
     * @author 段恩刚
     * @since 2.0.0 2018年12月20日08:59:03
     */

    public static String getCodes() {
        Random random = new Random();
        String result="";
        int codeLength=5;
        for (int i=0;i<codeLength;i++)
        {
            result+=random.nextInt(10);
        }
        return result;
    }

    /**
     *  对随机生成的建筑代码进行判重
     * @return 判重后的建筑代码
     * @author 段恩刚
     * @since 2.0.0 2018年12月20日08:59:03
     */
    private String isBuildingCodeExist(){
        //随机生成建筑代码
        String buildingCodeExist =getCodes();
        //查询此代码是否存在
        String queryCode=buildingService.findIdIsExist(buildingCodeExist,"");
        //设置最终的建筑代码
        String finalBuildingCode="";
        //如果建筑代码重复，就重新生成
        if(!StringUtils.isEmpty(queryCode)){
            while (!StringUtils.isEmpty(queryCode)){
                finalBuildingCode =getCodes();
            }
        }else{
            finalBuildingCode=buildingCodeExist;
        }
        return finalBuildingCode;
    }

    /**
     *  对随机生成的房间代码进行判重
     * @return 判重后的房间代码
     * @author 段恩刚
     * @since 2.0.0 2018年12月20日08:59:03
     */
    private String isRoomCodeExist(){
        //随机生成建筑代码
        String roomCodeExist =getCodes();
        //查询此代码是否存在
        String queryCode=roomService.findIdIsExist("",roomCodeExist);
        //设置最终的房间代码
        String finalRoomCode="";
        //如果建筑代码重复，就重新生成
        if(!StringUtils.isEmpty(queryCode)){
            while (!StringUtils.isEmpty(queryCode)){
                finalRoomCode =getCodes();
            }
        }else{
            finalRoomCode=roomCodeExist;
        }
        return finalRoomCode;
    }

    /**
     * 根据id查找Building
     * @param id 主键id
     * @author 段恩刚
     * @since 2.0.0 2018-11-08 19:34:10
     */
    @ApiOperation(value = "根据id查询")
    @GetMapping(value = {"/findById/{id}"})
    public ItooResult findById(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
        BuildingEntity buildingEntity = buildingService.getById(id);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", buildingEntity);
    }

    /**
     * 分页查询所有Building
     *
     * @param pageNo   页码
     * @param pageSize 每页条数
     * @author 段恩刚
     * @since 2.0.0 2018-11-08 19:34:10
     */
    @ApiOperation(value = "分页查询所有Building")
    @GetMapping(value = {"/queryPageAll/{pageNo}/{pageSize}"})
    public ItooResult queryPageAll(@ApiParam(name = "pageNo",value = "页码",required = true,example = "1")@PathVariable Integer pageNo,
                                   @ApiParam(name = "pageSize",value = "页数",required = true,example = "10")@PathVariable Integer pageSize) {
        PageInfo<BuildingEntity> buildings = buildingService.queryPageAll(pageNo, pageSize);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", buildings);
    }
	
	/**
     * 根据建筑名称模糊查询building
     * @param name  建筑名称
     * @param pageNo   页码
     * @param pageSize 页数
     * @return 模糊查询的building
     * @author 段恩刚
     * @since 2.0.0 2018-11-08 19:34:10
     */
    @ApiOperation(value = "根据建筑名称模糊查询building", notes = "分页根据建筑名称模糊查询building")
    @GetMapping(value = "queryBuildingByLikeName/{pageNo}/{pageSize}")
    public ItooResult queryBuildingByLikeName(@RequestParam(required = false, defaultValue = "") String name,
                                              @ApiParam(name = "pageNo",value = "页码",required = true,example = "1") @PathVariable Integer pageNo,
                                              @ApiParam(name = "pageSize",value = "页数",required = true,example = "10") @PathVariable Integer pageSize) {
        PageInfo<BuildingEntity> buildingList = buildingService.queryByLikeName(name, pageNo, pageSize);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", buildingList);
    }
    //endregion

    /* **********************************以下为非模板生成的内容********************************* */


    /**
     * 根据校区Id查询所有该校区的所有建筑
     *
     * @param schoolBranch 校区Id
     * @return buildingModel
     * @author 段恩刚
     * @since 2.0.0 2018-11-13 19:34:10
     */
    @ApiOperation(value = "根据校区查询该校区所有的建筑物", notes = "根据校区查询该校区所有的建筑物，这里查教学楼")
    @ApiImplicitParam(name="schoolBranch",value="校区",dataType = "string",required = true,example = "010")
    @GetMapping(value="queryAllBuildings/{schoolBranch}")
    public ItooResult queryAllBuildings(@PathVariable String schoolBranch){
       if (!schoolBranch.isEmpty()){
           List<BuildingModel> buildingModels= buildingService.queryAllBuildings(schoolBranch);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功",buildingModels);
       }else{
           return ItooResult.build(ItooResult.FAIL,"查询失败");
       }
   }
    /**
     * 根据前十条建筑信息
     * @param
     * @return buildingModel
     * @author 段恩刚
     * @since 2.0.0 2018-11-13 19:34:10
     */
    @ApiOperation(value = "查询前十条建筑信息", notes = "查询前十条建筑信息")
    @GetMapping(value="queryTop10Building")
    public ItooResult queryTop10Buildings(){
            List<BuildingModel> buildingModels= buildingService.queryTop10Buildings();
            return ItooResult.build(ItooResult.SUCCESS, "查询成功",buildingModels);
    }

    /**
     * 根据建筑名称查询建筑
     *
     * @param buildingName 建筑名称
     * @return buildingModel
     * @author 段恩刚
     * @since 2.0.0 2018-11-14 19:34:10
     */
    @ApiOperation(value = "根据建筑名称查询建筑", notes = "根据建筑名称查询建筑，这里查教学楼")
    @ApiImplicitParam(name="buildingName",value="建筑名称",dataType = "string",required = true,example = "数理楼")
    @GetMapping(value="queryBuildingByName/{buildingName}")
    public ItooResult queryBuildingByName(@RequestParam String buildingName){
        if (!buildingName.isEmpty()){
            List<BuildingModel> buildingModels= buildingService.queryBuildingByName(buildingName);
            return ItooResult.build(ItooResult.SUCCESS, "查询成功",buildingModels);
        }else{
            return ItooResult.build(ItooResult.FAIL,"查询失败");
        }
    }

    /**
     * 根据建筑类型查询建筑
     *
     * @param buildingType 建筑类型
     * @return buildingModel
     * @author 段恩刚
     * @since 2.0.0 2018-11-15 19:34:10
     */
    @ApiOperation(value = "根据建筑类型查询建筑", notes = "根据建筑类型查询建筑，这里查教学楼")
    @ApiImplicitParam(name="buildingType",value="建筑类型",dataType = "string",required = true,example = "000")
    @GetMapping(value="queryBuildingsByType/{buildingType}")
    public ItooResult queryBuildingsByType(@RequestParam String buildingType){
        if (!buildingType.isEmpty()){
            List<BuildingModel> buildingModels= buildingService.queryBuildingsByType(buildingType);
            return ItooResult.build(ItooResult.SUCCESS, "查询成功",buildingModels);
        }else{
            return ItooResult.build(ItooResult.FAIL,"查询失败");
        }
    }

    /**
     * 根据建筑名称或类型模糊查询building
     * @param buildingName  建筑名称
     * @param buildingType  建筑类型
     * @param pageNo   页码
     * @param pageSize 页数
     * @return buildingModel
     * @author 段恩刚
     * @since 2.0.0 2018-11-15 19:34:10
     */
    @ApiOperation(value = "根据建筑名称或类型模糊查询building", notes = "根据建筑名称或类型模糊查询building")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码", dataType = "int", required = true, example = "1"),
            @ApiImplicitParam(name = "pageSize", value = "记录数", dataType = "int", required = true, example = "10"),
            @ApiImplicitParam(name="buildingName",value="建筑名称",dataType = "string",required = true,example = "楼"),
            @ApiImplicitParam(name="buildingType",value="建筑类型",dataType = "string",required = true,example = "000")
            })
    @GetMapping(value = "queryBuildingsLikeNameOrType/{buildingName}/{buildingType}/{pageNo}/{pageSize}")
    public ItooResult queryBuildingsLikeNameOrType(@RequestParam(required = false, defaultValue = "") String buildingName,
                                                   @RequestParam(required = false, defaultValue = "") String buildingType,
                                                   @PathVariable Integer pageNo, @PathVariable Integer pageSize) {
        PageInfo<BuildingModel> buildingModels = buildingService.queryBuildingsLikeNameOrType(buildingName,buildingType, pageNo, pageSize);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功",buildingModels);
    }


    /**
     * 页面Roommanage加载时查询所有的buildingId
     * @param
     * @return buildingModel
     * @author 段恩刚
     * @since 2.0.0 2018-11-13 19:34:10
     */
    @ApiOperation(value = "页面Roommanage加载时查询所有的buildingId", notes = "页面Roommanage加载时查询所有的buildingId")
    @GetMapping(value="queryAllBuildingIds")
    public ItooResult queryAllBuildingIds(){
        List<BuildingModel> buildingModels= buildingService.queryAllBuildingIds();
        return ItooResult.build(ItooResult.SUCCESS, "查询成功",buildingModels);
    }
    /**
     * 场所管理页面的导出
     * @param
     * @return buildingModel
     * @author 段恩刚
     * @since 2.0.0 2018-11-13 19:34:10
     */
    @ApiOperation(value = "根据buildingName导出building信息")
    @GetMapping(value = {"/exportByLikeName"})
    public ItooResult exportByLikeName(HttpServletResponse response,
                                       @RequestParam(required =false,defaultValue = "")String buildingName){
        if (buildingService.exportByLikeName(buildingName,response)){
            return ItooResult.build(ItooResult.SUCCESS,"导出成功");
        }else {
            return ItooResult.build(ItooResult.FAIL,"导出失败");
        }
    }

    /**
     * 下载培养计划模板，批量导入使用
     *
     * @param response 响应
     * @return 下载模板是否成功
     * @author 段恩刚
     * @since 2.0.0 2018-11-15 08:53:53
     */
    @ApiOperation(value = "下载培养计划模板，批量导入使用", notes = "下载培养计划模板，批量导入使用")
    @GetMapping(value = {"/downLoadTemplate"})
    public ItooResult downLoadTemplate(HttpServletResponse response) {
        if (buildingService.downLoadTemplate(response)) {
            return ItooResult.build(ItooResult.SUCCESS, "下载培养计划模板成功");
        } else {
            return ItooResult.build(ItooResult.FAIL, "下载培养计划模板失败");
        }
    }

    /**
     * 批量导入建筑信息
     *
     * @param multipartFile 批量导入的文件
     * @param request       请求
     * @param response      响应
     * @return ItooResult 批量导入的结果
     * @author 段恩刚
     * @since 2.0.0 2018-11-27 09:05:59
     */
    @ApiOperation(value = "批量导入建筑信息", notes = "0001:部分成功；0000:成功；1111:失败")
    @PostMapping(value = {"/importBuildingInfoByTemplate"})
    public ItooResult importTrainingProgramsByTemplate(@RequestParam(value = "file") MultipartFile multipartFile,
                                                       HttpServletRequest request, HttpServletResponse response) {
        return buildingService.importTemplate(multipartFile, request, response);
    }

    /**
     * 导出-导入失败的数据
     *
     * @param response  响应
     * @param errorListId 为成功导入的分组id
     * @return 建筑信息model
     * @author 段恩刚
     * @since 2018.11.30 19:25
     */
    @ApiOperation(value = "导出-导入失败的数据")
    @GetMapping(value = "exportFile/downErrorList/{errorListId}")
    public ItooResult downErrorList(HttpServletResponse response,
                                    @ApiParam(name = "errorListId", value = "errorListId", required = true) @PathVariable String errorListId) {

        if (buildingService.downErrorList(errorListId,response)){
            return ItooResult.build(ItooResult.SUCCESS,"导出成功");
        } else {
            return ItooResult.build(ItooResult.FAIL,"导出失败");
        }

    }

    /**
     * 查询BuildingInfo的树形结构
     *
     * @return BuildingInfo的树形结构
     * @author 段恩刚
     * @since 1.0.0 2018-11-30 15:47:31
     */
    @ApiOperation(value = "查询所有场所信息的树形结构")
    @GetMapping(value = {"/queryBuildingInfoTreeModel"})
    public ItooResult queryBuildingInfoTreeModel() {
        List<FooGroupTreeModel> fooGroupTreeModels = buildingService.queryTreeModel();
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", fooGroupTreeModels);
    }

    /**
     * 添加树形结构数据
     *
     * @param fooGroupTreeModel 树形结构对象
     * @return 添加是否成功信息
     * @author 段恩刚
     * @since 1.0.0 2018年12月5日15:14:51
     */
    @ApiOperation("添加场所信息的树形结构信息")
    @PostMapping(value = {"/createTreeModel"})
    public ItooResult createTreeModel(@RequestBody FooGroupTreeModel fooGroupTreeModel){
        if (StringUtils.isEmpty(fooGroupTreeModel.getParentId())){
            log.warn("pid不能为空-fooGroupTreeModel{}"+fooGroupTreeModel);
            return ItooResult.build(ItooResult.FAIL,"pid为空");
        }
        if (StringUtils.isEmpty(fooGroupTreeModel.getName())){
            log.warn("节点名称不能为空-fooGroupTreeModel{}"+fooGroupTreeModel);
            return ItooResult.build(ItooResult.FAIL,"树节点名称为空");
        }

        RoomEntity roomEntity =new RoomEntity();
        BuildingEntity buildingEntity=new BuildingEntity();
        ValueEntity valueEntity=new ValueEntity();

        //判断级别，存入实体中
        //房间级别
        if(fooGroupTreeModel.getType().equals(typeRoom)){
            roomEntity.setName(fooGroupTreeModel.getName());
            roomEntity.setBuildingId(fooGroupTreeModel.getParentId());
            roomEntity.setIsDelete(0);
            roomEntity.setIsUsed(0);
            roomEntity.setRoomCapacity(0);
            roomEntity.setRoomType("普通教室");
            roomEntity.setCode(isRoomCodeExist());
            roomEntity.setId(IdWorker.getIdStr());
            roomService.save(roomEntity);
            //建筑楼级别
        }else if (fooGroupTreeModel.getType().equals(typeBuilding)){
            buildingEntity.setName(fooGroupTreeModel.getName());
            //建筑信息的id
            buildingEntity.setId(IdWorker.getIdStr());
            //建筑未删除
            buildingEntity.setIsDelete(0);
            buildingEntity.setCode(isBuildingCodeExist());
            buildingEntity.setType("000");
            buildingEntity.setSchoolBranch("011");
            buildingEntity.setIsComputerRoom(0);
            buildingService.save(buildingEntity);
            //建筑类型级别
        }else if(fooGroupTreeModel.getType().equals(typeBuildingType)){
            valueEntity.setName(fooGroupTreeModel.getName());
            valueEntity.setTypeId("11");
            valueEntity.setId(IdWorker.getIdStr());
            valueService.save(valueEntity);
        }else{
                 return null;
        }
        return ItooResult.build(ItooResult.SUCCESS,"添加成功");
    }

    /**
     * 根据id编辑fooGroupModel的树形结构
     *
     * @param fooGroupTreeModel 树形结构对象
     * @return 编辑结果
     * @author 段恩刚
     * @since 1.0.0 2018年12月5日15:14:43
     */
    @ApiOperation(value = "根据id编辑场所信息的树形结构信息")
    @PutMapping(value = {"/modifyTreeModel"})
    public ItooResult modifyTreeModel(@RequestBody FooGroupTreeModel fooGroupTreeModel){
        if (StringUtils.isEmpty(fooGroupTreeModel.getId())){
            log.warn("id为空，FooGroupTreeModel-{}"+fooGroupTreeModel);
            return ItooResult.build(ItooResult.FAIL,"id为空");
        }
        if (StringUtils.isEmpty(fooGroupTreeModel.getParentId())){
            log.warn("parentId为空，FooGroupTreeModel-{}"+fooGroupTreeModel);
            return ItooResult.build(ItooResult.FAIL,"parentId为空");
        }
        if (StringUtils.isEmpty(fooGroupTreeModel.getName())){
            log.warn("节点名称为空，FooGroupTreeModel-{}"+fooGroupTreeModel);
            return ItooResult.build(ItooResult.FAIL,"树节点名称为空");
        }

        //实例化三个需要进行保存的实体
        RoomEntity roomEntity =new RoomEntity();
        BuildingEntity buildingEntity=new BuildingEntity();
        ValueEntity valueEntity=new ValueEntity();


        //判断级别，存入实体中
        String treeType=fooGroupTreeModel.getType();
        if(treeType.equals(typeRoom)){
            roomEntity.setBuildingId(fooGroupTreeModel.getParentId());
            roomEntity.setId(fooGroupTreeModel.getId());
            roomEntity.setName(fooGroupTreeModel.getName());
            roomService.updateById(roomEntity);
        }else if (treeType.equals(typeBuilding)){
            buildingEntity.setType(fooGroupTreeModel.getParentId());
            buildingEntity.setId(fooGroupTreeModel.getId());
            buildingEntity.setName(fooGroupTreeModel.getName());
            buildingService.updateById(buildingEntity);
        }else if(treeType.equals(typeBuildingType)){
            valueEntity.setTypeId(fooGroupTreeModel.getParentId());
            valueEntity.setId(fooGroupTreeModel.getId());
            valueEntity.setName(fooGroupTreeModel.getName());
            valueService.updateById(valueEntity);
        }else{
            return null;
        }
        return ItooResult.build(ItooResult.SUCCESS,"编辑成功");
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @param type 类型type
     * @return ItooResult 是否删除成功
     * @author 段恩刚
     * @since 1.0.0 2018年12月5日15:25:22
     */
    @ApiOperation(value = "删除场所信息的树形结构信息")
    @DeleteMapping(value = {"/delete/{id}/{type}"})
    public ItooResult delete(@ApiParam(value = "主键id", required = true) @PathVariable String id,
                             @ApiParam(value = "级别type", required = true) @PathVariable String type) {
        //判断级别，然后进行删除
        if(type.equals(typeRoom)){
            roomService.removeById(id);
        }else if (type.equals(typeBuilding)){
            buildingService.removeById(id);
        }else if(type.equals(typeBuildingType)){
            valueService.removeById(id);
        }
        return ItooResult.build(ItooResult.SUCCESS, "删除成功");
    }
}

